package com.rybbaby.tss.front.tssMemberAddSubtractRecord.controller;

import com.google.common.collect.ImmutableMap;
import com.rybbaby.tss.core.annotation.RequestLog;
import com.rybbaby.tss.core.annotation.Token;
import com.rybbaby.tss.core.annotation.validator.RegexpValidator;
import com.rybbaby.tss.core.annotation.validator.StringValidator;
import com.rybbaby.tss.core.bean.PageBean;
import com.rybbaby.tss.core.hqlsearch.HqlGenerateUtil;
import com.rybbaby.tss.core.utils.AjaxJsonResponse;
import com.rybbaby.tss.core.utils.PropertiesReadUtil;
import com.rybbaby.tss.core.utils.SequenceUtil;
import com.rybbaby.tss.core.utils.StringUtils;
import com.rybbaby.tss.core.web.controller.BaseController;
import com.rybbaby.tss.front.tssMemberAddSubtractRecord.entity.TssMemberAddSubtractRecord;
import com.rybbaby.tss.front.tssMemberAddSubtractRecord.service.ITssMemberAddSubtractRecordService;
import com.rybbaby.tss.front.tssMemberAttendClassRecord.entity.TssMemberAttendClassRecord;
import com.rybbaby.tss.front.tssMemberAttendClassRecord.service.ITssMemberAttendClassRecordService;
import com.rybbaby.tss.front.tssMemberPackage.entity.TssMemberPackage;
import com.rybbaby.tss.front.tssMemberPackage.service.ITssMemberPackageService;
import com.rybbaby.tss.front.tssRightStatistic.service.ITssRightStatisticService;
import com.rybbaby.tss.platform.sysAdminUser.entity.SysAdminUser;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Member;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 雷春琼
 * @description 会员加减课时记录表管理
 * @createDate 2017-08-09 下午11:59:34
 */
@Controller
@RequestMapping(value = "tssMemberAddSubtractRecordController")
public class TssMemberAddSubtractRecordController extends BaseController {

    @Autowired
    private ITssMemberAddSubtractRecordService tssMemberAddSubtractRecordService;
    @Autowired
    private ITssRightStatisticService tssRightStatisticService;
    @Autowired
    private ITssMemberPackageService tssMemberPackageService;


    /**
     * 获取会员加减课时记录表列表
     *
     * @return
     * @throws IOException
     */
    @RequestLog(content = "获取会员加减课时记录表列表", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "tssMemberAddSubtractRecordList", method = RequestMethod.POST)
    public ModelAndView tssMemberAddSubtractRecordList(TssMemberAddSubtractRecord entity, PageBean paramPageBean) {
        ModelAndView mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssMemberAddSubtractRecordListView"));
        try {
            Map<String, String[]> unLockMap = getParameterMap(request);
            DetachedCriteria dc = DetachedCriteria.forClass(TssMemberAddSubtractRecord.class);
            HqlGenerateUtil.fillDetachedCriteria(dc, entity, unLockMap);
            PageBean pageBean = tssMemberAddSubtractRecordService.pageList(dc, paramPageBean.getPageNo(), paramPageBean.getPageSize());
            mav.addObject(super.SEARCH_MAP, unLockMap);
            mav.addObject(super.PAGE_BEAN, pageBean);
            mav.addObject("searchFormId", SEARCH_FORM);
            mav.addObject("actionUrl", request.getRequestURI());
            mav.addObject("pagingBar", pageBean.getPagingBar(SEARCH_FORM));
            mav.addObject("serializeNum", SequenceUtil.getUpperCaseUUID());
            String requestURI = StringUtils.substringBeforeLast(request.getRequestURI(), "/");
            mav.addObject("editUrl", requestURI + "/toEditView.do");
            mav.addObject("deleteUrl", requestURI + "/delete.do");
            mav.addObject("batchDeleteUrl", requestURI + "/batchDelete.do");
        } catch (Exception e) {
            throw e;
        }
        return mav;
    }

    /**
     * 转到编辑视图
     *
     * @param memberPackageId       接收编辑参数的临时对象
     * @param serializeNum 请求标识
     * @return
     */
    @RequestLog(content = "转到会员加减课时记录表视图", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "toEditView", method = RequestMethod.GET)
    public ModelAndView toEditView(@RequestParam(required = true) String memberPackageId, @RequestParam(required = true) String serializeNum, @RequestParam(required = true) Integer type, @RequestParam(required = true) Integer addSubtractType) {
        ModelAndView mav = null;
        if (type == 1 && addSubtractType == 1) {
            mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssMemberAddRecordEditView"));
        } else if (type == 1 && addSubtractType == 2) {
            mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssMemberSubtractRecordEditView"));
        } else if (type == 2 && addSubtractType == 1) {
            mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitMemberAddRecordEditView"));
        } else if (type == 2 && addSubtractType == 2) {
            mav = new ModelAndView(PropertiesReadUtil.getStringProperty("tssTransitMemberSubtractRecordEditView"));
        }
        TssMemberPackage memberPackage=this.tssMemberPackageService.get(memberPackageId);
        mav.addObject("data", memberPackage);
        mav.addObject("memberPackageId", memberPackageId);
        mav.addObject("editModel", "add");
        mav.addObject("serializeNum", serializeNum);
        mav.addObject("saveUrl", StringUtils.substringBeforeLast(request.getRequestURI(), "/") + "/saveOrUpdate.do");
        return mav;
    }

    /**
     * 保存编辑的对象
     *
     * @param entity 被编辑对象
     * @return
     */
    @ResponseBody
    @RequestLog(content = "保存会员加减课时记录表对象", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
    public String saveOrUpdate(TssMemberAddSubtractRecord entity) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        String adminUserId = super.getLoginUser().getId();
        try {
            String id = entity.getId();
            ajr.setResMsg("保存成功!");
            entity.setCreateTime(new java.sql.Timestamp(System.currentTimeMillis()));
            entity.setAdminUserId(super.getLoginUser().getId());
            Serializable newId = this.tssMemberAddSubtractRecordService.save(entity, adminUserId);

            //修改课时包正课，赠课，补课课时
            Integer classHourType = entity.getClassHourType();
            String memberPackageId = entity.getMemberPackageId();
            //加减课时权责
            if (classHourType != null && entity.getClassHour() != null) {
                if (entity.getClassHourType() == 1) {
                    //课时包退费权责
                    HashMap<String, Object> map = new HashMap<>();
                    Integer type = 0;
                    Integer responsibilityType = 0;
                    TssMemberPackage tssMemberPackage = tssMemberPackageService.get(memberPackageId);
                    map.put("nowUnitPrice", tssMemberPackage.getNowUnitPrice());
                    map.put("expendClassHour", entity.getClassHour());
                    if (tssMemberPackage != null) {
                        map.put("memberId", tssMemberPackage.getMemberId());
                        map.put("memberPackageId", tssMemberPackage.getId());
                        if (entity.getEmpAdminUserId() != null) {
                            if (tssMemberPackage.getType() == 1) {
                                type = 1;
                                responsibilityType = 3;
                            }
                            if (tssMemberPackage.getType() == 2) {
                                type = 2;
                                responsibilityType = 6;
                            }
                        } else {
                            type = 7;
                            responsibilityType = 14;
                        }
                    }
                    boolean c = tssRightStatisticService.saveOrUpdateTssRightStatisticService(null, map, adminUserId, type, responsibilityType, 0, null);
                }
            }
            if (newId == null) {
                ajr.setResCode(301);
                ajr.setResMsg("保存失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("保存失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 删除指定id的对象
     *
     * @param id 需要被删除的对象id
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String delete(@StringValidator(nullable = false) String id) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(id)) {
                this.tssMemberAddSubtractRecordService.deleteEntityById(id);
            } else {
                ajr.setResMsg("删除失败!");
                ajr.setResCode(302);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

    /**
     * 批量删除指定id的对象
     *
     * @param ids 需要被删除的对象id组成的字符串
     * @return
     */
    @ResponseBody
    @RequestLog(content = "删除属性", save = true)
    @Token(validateToken = false)
    @RequestMapping(value = "batchDelete", method = RequestMethod.GET)
    public String batchDelete(@RegexpValidator(nullable = false, regexp = "^(\\w+,?)+\\w+$") String ids) {
        AjaxJsonResponse ajr = new AjaxJsonResponse();
        try {
            ajr.setResMsg("删除成功!");
            if (StringUtils.isNotBlank(ids)) {
                boolean batchDelete = this.tssMemberAddSubtractRecordService.batchDelete(ids.split(","));
                if (!batchDelete) {
                    ajr.setResMsg("删除失败!");
                    ajr.setResCode(302);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajr.setResCode(500);
            ajr.setResMsg("删除失败(" + e.getMessage() + ")!");
        }
        return ajr.jsonResponse(false);
    }

}
